using AdminApiTemplate.Api.Controllers.BaseControllers;
using AdminApiTemplate.Api.Enums;
using AdminApiTemplate.Api.Helpers;
using AdminApiTemplate.Cache;
using AdminApiTemplate.Common.Exceptions;
using AdminApiTemplate.Services.SysConfig;
using Microsoft.AspNetCore.Mvc;

namespace AdminApiTemplate.Api.Controllers
{
    /// <summary>
    /// 首页（无需登录）
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class HomeController : FreeAccessController
    {
        private readonly SysConfigService _sysConfigService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sysConfigService"></param>
        public HomeController(
            SysConfigService sysConfigService)
        {
            _sysConfigService = sysConfigService;
        }

        /// <summary>
        /// 刷新配置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("RefreshConfig")]
        public IActionResult RefreshConfig()
        {
            return new WebHelper(HttpContext, null, false).Execute(SysUserTypeEnum.None, string.Empty, () =>
            {
                var items = _sysConfigService.InitSysConfigAsync().Result;
                var cacheItems = items.Select(o => new SysConfigItem
                {
                    KeyName= o.KeyName,
                    Val= o.Val
                }).ToList();
                ConfigHelper.Init(cacheItems);
                return "操作成功";
            });
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="module"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("Download")]
        public IActionResult Download(string module, string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "fileName必填");
            }

            string fullName;
            if (!string.IsNullOrEmpty(module))
            {
                fullName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Uploads", module, fileName);
            }
            else
            {
                fullName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Uploads", fileName);
            }

            if (!System.IO.File.Exists(fullName))
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "文件地址错误，请稍后再试");
            }

            var bytes = System.IO.File.ReadAllBytes(fullName);
            return File(bytes, "application/octet-stream", fileName);
        }

        /// <summary>
        /// 导出文件
        /// </summary>
        /// <param name="module"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("Export")]
        public IActionResult Export(string module, string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "fileName必填");
            }

            string fullName;
            if (!string.IsNullOrEmpty(module))
            {
                fullName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Exports", module, fileName);
            }
            else
            {
                fullName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Exports", fileName);
            }

            if (!System.IO.File.Exists(fullName))
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "文件地址错误或者文件正在生成，请稍后再试");
            }

            var bytes = System.IO.File.ReadAllBytes(fullName);
            return File(bytes, "application/octet-stream", fileName);
        }
    }
}
